package com.laikan.library.components.activitys;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import com.laikan.library.R;
import com.laikan.library.components.dialog.LoadingDialog;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.managers.ActivityMgr;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public abstract class BasicActivity extends AppCompatActivity implements OnClickListener {

    protected Context mContext;
    protected Activity mActivity;
    protected String TAG;
    private boolean isEventBusOpen = false;
    private boolean isLocalBroadcastReceiverOpen = false;
    private BroadcastReceiver local_activity_receiver;
    private boolean isRestart = true;
    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Long timeStart = System.currentTimeMillis();
        mContext = this;
        mActivity = this;
        TAG = this.getClass().getSimpleName();
        KLog.d(TAG + "   create");
        KLog.d(TAG, "容器里activity 的数量：=" + ActivityMgr.getInstance().getActivityCount() + "个");
//        checkPermission();
        init();
        KLog.i("界面渲染耗时:" + (System.currentTimeMillis() - timeStart) + " ms");
        mLoadingDialog = new LoadingDialog(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //        getMenuInflater().inflate(R.menu.menu_basic, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isRestart) {
            initData();
            setListener();
            isRestart = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    private void init() {

        assignViews();
    }

    protected void checkPermission() {}

    /**
     * 加载布局和初始化View组件
     */
    protected abstract void assignViews();

    /**
     * 初始化View组件数据
     */
    protected abstract void initData();

    /**
     * 为组件注册监听
     */
    protected abstract void setListener();

    /**
     * 处理onClick事件
     */
    protected void onClickEvent(View view) {}

    ;

    protected void goToActivity(Class<? extends Activity> cls) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        startActivity(intent);
    }

    protected void sendLocalBroadCastReceiver(Intent intent) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (isEventBusOpen) {

            EventBus.getDefault().unregister(this);
            isEventBusOpen = false;
        }

        if (isLocalBroadcastReceiverOpen) {

            LocalBroadcastManager.getInstance(this).unregisterReceiver(local_activity_receiver);
            isLocalBroadcastReceiverOpen = false;
        }
        isRestart = true;
    }

    @Override
    public void finish() {

        super.finish();
        ActivityMgr.getInstance().removeActivity(this);
        KLog.d(TAG + "   finish");
        KLog.d("容器里activity 的数量：=" + ActivityMgr.getInstance().getActivityCount() + "个");
    }

    @Override
    public void onClick(View view) {

        onClickEvent(view);
    }

    public void openBroadcastReceiver(String action) {

        if (!isLocalBroadcastReceiverOpen) {

            local_activity_receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    parseLocalBroadCast(intent);
                }
            };
            LocalBroadcastManager.getInstance(this).registerReceiver(local_activity_receiver, new IntentFilter(action));
            this.isLocalBroadcastReceiverOpen = true;
        }
    }

    protected void parseLocalBroadCast(Intent intent) {}

    ;

    public void openEventBus() {
        if (!isEventBusOpen) {

            EventBus.getDefault().register(this);
            this.isEventBusOpen = true;
        }
    }

    public void postEvent(BasicEvent event) {
        EventBus.getDefault().post(event);
    }

    /**
     * EventBus 的解析器
     *
     * @param event
     */
    protected void parseEvent(BasicEvent event) {}

    ;

    protected void parseMainThreadEvent(BasicEvent event) {}

    ;

    protected void parseBackgroundEvent(BasicEvent event) {}

    ;

    protected void parseAsyncEvent(BasicEvent event) {}

    ;

    @Subscribe
    public void onEvent(BasicEvent event) {

        parseEvent(event);
    }

    @Subscribe
    public void onEventMainThread(BasicEvent event) {

        parseMainThreadEvent(event);
    }

    @Subscribe
    public void onEventBackground(BasicEvent event) {

        parseBackgroundEvent(event);
    }

    @Subscribe
    public void onEventAsync(BasicEvent event) {

        parseAsyncEvent(event);
    }

    /**
     * 打开加载框
     */
    public void showDialog() {
        KLog.e("show Dialog");
        if (null != mLoadingDialog && !mLoadingDialog.isShowing() && !isFinishing()) {
            mLoadingDialog.show();
        }
    }

    /*** 关闭加载框
     */
    public void dismissDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            try {
                mLoadingDialog.dismiss();
            }catch (Exception ignored) {
            }
        }
    }
}
